import cv2 as cv

img_color = cv.imread("image/test1.png")
img_sub = cv.imread("image/test1sub.png")

# 创建SIFT 特征检测对象
sift = cv.SIFT.create()
# 计算图片的特征点
keypoints, descriptors =  sift.detectAndCompute(img_color, None)
sub_keypoints, sub_descriptors =  sift.detectAndCompute(img_sub, None)

# 创建暴力匹配器
bf = cv.BFMatcher()

# knn检测  k是匹配数
matchs = bf.knnMatch(descriptors, sub_descriptors, k = 2)
print(type(matchs))
# 筛选更好的匹配位置
good_match = []
good_points = []
for m,n in matchs:
    if m.distance < n.distance * 0.009:
        good_match.append(m)
        # 获取最好的坐标点
        points = keypoints[m.queryIdx].pt
        good_points.append(points)

for a in good_points:
    b = (int(a[0]), int(a[1]))
    print(b)
    cv.rectangle(img_color, b, b, (0, 0, 255), 2)

# 绘制匹配到的特征点
dw_img = cv.drawMatches(img_color, keypoints, img_sub, sub_keypoints, good_match, None)
cv.imshow("dw_img" , dw_img)

cv.imshow("img_color", img_color)

cv.waitKey()
cv.destroyAllWindows()